<?php

//时间格式化函数
function fmDate($date){
	return date('m-d',$date);
}

//空过虑
function ComIsNull($data=''){
	
}

/**
 * json
 *
 * @param mixed $flag
 * @param mixed $info
 * @param mixed $database
 * @param mixed $argu1
 * @param mixed $argu2
 * @return void
 */
 if(!function_exists('json')){
	function json($status = null, $tips = null,$data=null,$url='/'){
			$result['status']         = $status;
			$result['tips'] 		= $tips;
			$result['data']			= $data;
			$r = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) : '';
			$inAjax = $r == 'xmlhttprequest';
			//if($inAjax){
				echo (json_encode( $result ));exit;
			//}else{
				//header("Location:$url");exit;
			//}
	}
 }
 if(!function_exists('dbg')){
	function dbg($data='',$f=false){
	echo '<pre>';
	print_r($data);
	if(!$f)
	exit;
}
 }
//用户头像
function uicon($uid,$app_avatar='',$type='newzan'){
	switch($type){
		case 'newzan':
			if(trim($uid) == null)return '/icon/0/0/0';
			$dir1 = floor(intval($uid)/1000000);
			$dir2 = floor(intval($uid)/1000);
			$file = AVATAR . DS . $dir1 . DS . $dir2 . DS . $uid . '.jpg';
			if(!is_file($file)){
				$path = "/HTML/pics/top_usericon.jpg";
			}else{
				$path = "/photo/avatar/".$dir1.'/'.$dir2.'/'.$uid . '.jpg';
			}
			$prefix = getHeader();
			$avatar = $prefix . $path;
			return ($avatar);
			break;
		case 'sina':
			return $app_avatar;
			break;
	}
	
}
//用户头像相对路径
function uiconpath($uid){
	if(trim($uid) == null)return '/icon/0/0/0';
	$dir1 = floor(intval($uid)/1000000);
	$dir2 = floor(intval($uid)/1000);
	$path = "avatar/".$dir1.'/'.$dir2.'/'.$uid;
	$opath = "avatar/".$dir1.'/'.$dir2;
	if(is_dir(DIR_PHOTO . DS . $opath)==false){
			@mkdir(DIR_PHOTO . DS . $opath,0700,1);
		}
	return $path;
}
//当前的URL
function getHeader(){
	$host = 'http://'.$_SERVER['HTTP_HOST'];
	//$host = str_replace("localhost","127.0.0.1",$host);
	return $host;
}
if( !function_exists('character_limiter')){
function character_limiter( $str, $len = 0, $dot = false, $encoding = 'utf-8' ) {
        $str = strip_tags( htmlspecialchars_decode($str) );
        $str = str_ireplace(array('&amp;', '&quot;', '&lt;', '&gt;','&nbsp;'), array(), $str);
		$str = trim($str);
		$strlen = strlen($str);
        if ( !$len || $strlen <= $len ) return $str;
        if ($encoding == 'utf-8') {
			$tmpStr = $str;
			$nowStr = '';
                $start = 0;
                while($start < $len) {
                        $t = ord($str[$start]);
						//dbg($str[4],true);dbg($t,true);dbg(chr($t),true);$ssss .= substr($str,4,3);dbg($ssss);
                        if($t == 9 || $t == 10 || (32 < $t && $t <= 126)) {
								$nowStr .= substr($tmpStr,0,1);
                                 $start++;
								$tmpStr = substr($str,$start,$strlen);
                        } elseif (194 <= $t && $t <= 253) {
								$nowStr .= substr($tmpStr,0,3);
                                $start += 3;
								$tmpStr = substr($str,$start,$strlen);
                        } else {
							$start++;
							$tmpStr = substr($str,$start,$strlen);
                        } 
                }
				if($strlen > $len){
					return $nowStr.$dot;
				}else{
					return $nowStr;
				}
        } elseif ($encoding == 'gbk') {
                for ($i=0; $i<$len; $i++) {
                        $nowStr .= ord($str{$i}) > 127 ? $str{$i}.$str{++$i} : $str{$i};
                }
        }
        $nowStr = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $nowStr);
        return $nowStr.$dot;
}
}
if( !function_exists('authRedirect')){
	function authRedirect($redirect){
		$ci = & get_instance();
		if(!$ci->auth->loged || !$ci->auth->admin){
			$ci->session->set_userdata('redirect',$redirect);
			redirect('/sign');
		}
	}
}
if( !function_exists('auth')){
	function auth($redirect){
		$ci = & get_instance();
		if(!$ci->auth->loged){
			$ci->session->set_userdata('redirect',$redirect);
			redirect('/sign');
		}
	}
}


if( !function_exists('getPhotoExif') ){
	function getPhotoExif($filepath){
		return array();
		if(!($filepath)){return array();}
		$_img = getimagesize($filepath);
		$exif['filesize'] = filesize($filepath);//文件大小
		$exif['width'] = $_img[0]; //照片宽
		$exif['height'] = $_img[1]; //照片宽
		$exif['filetype'] = $_img[2];//文件类型
		$exif['minetype'] = $_img['mime'];//文件格式
		
		if($exif['filetype'] == 2){
			$exif_jpeg  = exif_read_data($filepath);//读取文件的EXIF信息
		}


		if($exif_jpeg){
			if(isset($exif_jpeg['DateTime'])){
				$exif['datetime'] = $exif_jpeg['DateTime'];//拍照时间
			}elseif(isset($_exif['DateTimeOriginal'])){
				$exif['datetime'] = $exif_jpeg['DateTimeOriginal'];//拍照时间
			}elseif(isset($_exif['DateTimeDigitized'])){
				$exif['datetime'] = $exif_jpeg['DateTimeDigitized'];//拍照时间
			}
			$exif['exif_jpeg'] = $exif_jpeg;
			unset($exif['exif_jpeg']['MakerNote']);
		}else{
			$exif['datetime'] = '';//拍照时间
		}
		return $exif;
	}
}

if( !function_exists('getPhotoPath') ){
	function getPhotoPath($time,$pname){
		$time_to_path = timeToPath($time);
		$path = HTTP_IMAGE . 'photo/post/' .$time_to_path . '/' . $pname;
		return $path;		
	}
}
if( !function_exists('getThumbPath') ){
	function getThumbPath($time,$pname){
		$time_to_path = timeToPath($time);
		$path = HTTP_IMAGE . 'photo/post/' .$time_to_path . '/thumb/100X75_' . $pname;
		return $path;		
	}
}

if( !function_exists('timeToPath') ){
	function timeToPath($time){
		$time = date('Y/m',$time);
		return $time;
	}
}


 function getJson($key='',$jsondata='',$default=''){
		$temp = json_decode($jsondata);
		if(isset($temp->$key) && $temp->$key){
			return $temp->$key;
		}
		return $default;
	}

function getVideoPath($news_info,$time){
	$path = getJson('video_thumb',$news_info);
	if($path){
		if(strpos("http",$path))
			return $path;
		else
			return getHeader() . '/photo/post/' .timeToPath($time) . '/' . $path;
	}

}

function stringToUTF8($string){
	$code = array("ASCII","GBK","UTF-8");
	foreach($code as $c){
		$result = @iconv($c,'UTF-8//IGNORE',$string);
		if($result){
			if($string === @iconv('UTF-8//IGNORE',$c,$result)){
				return $result;
			}
		}
	}
	return $string;
}

// Returns true if $string is valid UTF-8 and false otherwise.
function is_utf8($string) {

	// From http://w3.org/International/questions/qa-forms-utf-8.html
	return preg_match('%^(?:
		[\x09\x0A\x0D\x20-\x7E] # ASCII
		| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
		| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
		| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
		| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
		| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
		| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
		| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
		)*$%xs', $string);

} // function is_utf8


/**
* js编码实现
*
* @param string $str
* @return string
*/ 
function escape($str) {
	preg_match_all("/[\xc2-\xdf][\x80-\xbf]+|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}|[\x01-\x7f]+/e",$str,$r);
	//匹配utf-8字符，
	$str = $r[0];
	$l = count($str);
	for($i=0; $i<$l; $i++){
		$value = ord($str[$i][0]);
		if($value < 223){
			$str[$i] = rawurlencode(utf8_decode($str[$i]));
			//先将utf8编码转换为ISO-8859-1编码的单字节字符，urlencode单字节字符.
			//utf8_decode()的作用相当于iconv("UTF-8","CP1252",$v)。
		}else{
			$str[$i] = "%u".strtoupper(bin2hex(iconv("UTF-8","UCS-2",$str[$i])));
		}
	}
	return join("",$str);
}

/**
* js解码实现
*
* @param string $str
* @return string
*/ 
function unescape($str) {
	$str = rawurldecode($str); 
	preg_match_all("/%u.{4}|&#x.{4};|&#d+;|.+/U",$str,$r); 
	$ar = $r[0]; 
	foreach($ar as $k=>$v) { 
		if(substr($v,0,2) == "%u") 
			$ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,-4))); 
		elseif(substr($v,0,3) == "&#x") 
			$ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,3,-1))); 
		elseif(substr($v,0,2) == "&#") { 
			$ar[$k] = iconv("UCS-2","UTF-8",pack("n",substr($v,2,-1))); 
		} 
	} 
	return join("",$ar); 
}

if( !function_exists('fastcgi_finish_request')){
	function fastcgi_finish_request(){;}
}


//生成$length位随机数
if( !function_exists('randomkeys')){
	function randomkeys($length){
		$key='';
		$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
		for($i=0;$i<$length;$i++){
			$key .= $pattern{rand(0,35)};
		}
		return $key;
   }
}
if( !function_exists('cutChart')){
	function cutChart($original_path,$save_path='',$save_name='',$width=100,$height=75){

		if( !$save_path or !$save_name ){
			return false;
		}
		if(is_resource($original_path)){
			return false;
		}else if(is_file($original_path)){

			$saveChartPath = $save_path . $save_name;
			$_img = getimagesize($original_path);
			$_original['width'] = $_img[0]; //照片宽
			$_original['height'] = $_img[1]; //照片宽
			$_original['filetype'] = $_img[2];//文件类型
			$_original['minetype'] = $_img['mime'];//文件格式
			$old_img = createImage($original_path, $_original['filetype']);
		
			if (function_exists("imagecreatetruecolor")) {
				$new_image = imagecreatetruecolor($width, $height);
				ImageCopyResampled($new_image, $old_img, 0, 0, 0, 0, $width, $height, $_original['width'], $_original['height']);
			} else {
				$new_image = imagecreatetruecolor($width, $height);
				ImageCopyResampled($new_image, $old_img, 0, 0, 0, 0, $width, $height, $_original['width'], $_original['height']);
			}

			if (file_exists($saveChartPath)) @unlink($saveChartPath);
			$result = ImageJPEG($new_image,$saveChartPath);
			ImageDestroy($new_image);
			return $result;
			
		}
	}
}
if( !function_exists('createImage')){
	function createImage($photo,$filetype){
		switch($filetype){
			case '1'://gif
				$image = imagecreatefromgif($photo);break;
			case '2'://jpeg,jpe
				$image = imagecreatefromjpeg($photo);break;
			case '3'://png
				$image = imagecreatefrompng($photo);break;
			case '6'://bmp
				$image = imagecreatefrombmp($photo);break;
			default:
				$image='';
		}
		return $image;
	}
}
if( !function_exists('jsonUpdate')){
function jsonUpdate($old_json_data, $now_data, $type='modify'){
		if(!$old_json_data){
			$temp = array();
		}else{
			$temp = json_decode($old_json_data,true);
		}
		switch($type){
			case 'increment': //某一个什增一
				if(isset($temp[$now_data])){
					$temp[$now_data]++;
				}else{
					$temp[$now_data] = '1';
				}
				return json_encode($temp);
				break;
			case 'modify': //修改里面的一个键值
				foreach($now_data as $key => $value){
					if(isset($temp[$key]) && $now_data[$key]){ //本来有已经有这个键值,并且有值 
						$temp[$key] = $now_data[$key];
					}else if(!$now_data[$key]){//如果这个值为空，则删除这个键
						unset($temp[$key]);
					}else{//新加入这个值
						$temp[$key] = $now_data[$key];
					}
				}
				return json_encode($temp);
		}
	}
}
